package com.xiangb.springbootjpa.utils;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;

/**
 * Description: <br>
 *
 * @author: XB
 * @date: 2021/7/7 15:27
 */
public class JudgeCharsetUtils {
    /**
     * 根据文件路径返回文件编码
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String getCharset(String filePath) throws IOException {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(
                filePath));
        int p = (bin.read() << 8) + bin.read();
        String code = null;

        switch (p) {
            case 0xefbb:
                code = "UTF-8";
                break;
            case 0xfffe:
                code = "Unicode";
                break;
            case 0xfeff:
                code = "UTF-16";
                break;
            default:
                code = "GB2312";
        }
        System.out.println(code);
        return code;
    }

    /**
     * 读取txt文件内容
     * @param file
     * @return
     * @throws Exception
     */
    public static String txt2String(File file) throws Exception {
        String result = "";
        //构造一个BufferedReader类来读取文件
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(file), "GB2312");
        BufferedReader reader = new BufferedReader(inputStreamReader);
        String s = null;
        //使用readLine方法，一次读一行
        while ((s = reader.readLine()) != null) {
            result = result + "\n" + s;
        }
        reader.close();
        return result;
    }

    /**
     * 以指定编码方式写文本文件，存在会覆盖
     *
     * @param file
     *            要写入的文件
     * @param toCharsetName
     *            要转换的编码
     * @param content
     *            文件内容
     * @throws Exception
     */
    public static void saveFile2Charset(File file, String toCharsetName,
                                        String content) throws Exception {
        if (!Charset.isSupported(toCharsetName)) {
            throw new UnsupportedCharsetException(toCharsetName);
        }
        OutputStream outputStream = new FileOutputStream(file);
        //增加头文件标识
        outputStream.write(new byte[]{(byte)0xEF, (byte)0xBB, (byte)0xBF});
        OutputStreamWriter outWrite = new OutputStreamWriter(outputStream,
                toCharsetName);
        outWrite.write(content);
        outWrite.close();
    }
}
